package org.vectrics.common.util;

import java.util.Arrays;
import java.util.zip.Adler32;
import org.apache.log4j.Logger;

//import com.kenmccrary.jtella.util

/**
 *  Represents a unique ID
 *
 */
public class GUID
{
  private short[] data;
  private transient static Logger log = Logger.getLogger(GUID.class);

  
  public static String create() {
      GUID newGuid = new GUID();
      return(newGuid.toString());
  }
  
  /**
   *  Construct a new GUID
   *
   */
  public GUID()
  {
     data = Utilities.generateGUID();
     if (log.isDebugEnabled()) {
     	log.debug("GUID - " + toString());
     }
  }


  /**
   *  Create a guid from network data
   *
   *
   */
  public GUID(short[] data)
  {
    this.data = data;
  }

  /**
   *  Query the bytes in this GUID
   *
   *  @return bytes
   */
  private short[] getData()
  {
    return data;
  }

  /**
   *  Compare guids
   *
   */
  public boolean equals(Object obj)
  {
    if ( !(obj instanceof GUID) ) 
    {
      return false;
    }

    // Check if the data is the same
    GUID rhs = (GUID)obj;
    short[] lhsData = getData();
    short[] rhsData = rhs.getData();

    return Arrays.equals(lhsData, rhsData);
  }

  /**
   *  Produce a hashcode for this GUID
   *
   */
  public int hashCode() 
  {
    Adler32 adler32 = new Adler32();

    // todo fix this stuff
    byte[] tempData = new byte[data.length];

    for (int i = 0; i < data.length; i++) 
    {
      tempData[i] = (byte)data[i];
    }

    adler32.update(tempData);

    return (int)adler32.getValue();
  }

  
  /**
   *  Returns a GUID as a String
   *
   *  @return text form of guid
   */
  public String toString() {
    StringBuffer message = new StringBuffer();

    // Divide the array of integers into several longs
    long num = 0;
    for (int i = 0; i < 7; i++) {
        num = (num * 10) + data[i];
    }
    String h = Long.toHexString(num);
    while (h.length() < 4) {
        h = "0" + h;
    }
       
    num = 0;
    for (int i = 7; i < 14; i++) {
        num = (num * 10) + data[i];
    }
    String l = Long.toHexString(num);
    while (l.length() < 7) {
        l = "0" + l;
    }
       
    num = 0;
    for (int i = 14; i < 16; i++) {
        num = (num * 10) + data[i];
    }
    String m = Long.toHexString(num);
    while (m.length() < 2) {
        m = "0" + m;
    }
    
    // Concatenate the three long hex's into string that is the new GUID 
    return h + m + l; 
  }
  
  
} 

